package com.mlink.ai.chat.ui.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Vibrator
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.ActivityHistoryBinding
import com.mlink.ai.chat.constants.MYSELF_URL_IN_GOOGLE_PLAY
import com.mlink.ai.chat.ui.adapter.ChatItem
import com.mlink.ai.chat.ui.adapter.ChatRecyclerAdapter
import com.mlink.ai.chat.ui.adapter.ChatType
import com.mlink.ai.chat.ui.fragment.SelectShareBottomDialogFragment
import com.mlink.ai.chat.utils.AnalyticsEvents
import com.mlink.ai.chat.utils.BitmapUtils
import com.mlink.ai.chat.utils.FileUtils
import com.mlink.ai.chat.utils.logEvent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class HistoryActivity : BaseActivity<ActivityHistoryBinding>() {

    private var isHandleShare = false // 是否正在生成分享的图片
    private lateinit var adapter: ChatRecyclerAdapter
    private var selectShareFragment: SelectShareBottomDialogFragment? = null


    override fun getViewBinding(): ActivityHistoryBinding =
        ActivityHistoryBinding.inflate(layoutInflater)

    override fun initViews() {
        binding.run {
            ivBack.setOnClickListener {
                finish()
            }

            ivShare.setOnClickListener {
                clickShare()
            }

            adapter = ChatRecyclerAdapter().apply {
                listener = object : ChatRecyclerAdapter.ChatFunctionListener {
                    override fun onCopyContent(item: ChatItem) {
                        runCatching {
                            val cbm =
                                getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                            item.content?.answer?.let {
                                cbm.setPrimaryClip(ClipData.newPlainText(null, it))
                                val vibrator =
                                    getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
                                    Toast.makeText(
                                        this@HistoryActivity,
                                        this@HistoryActivity.resources.getString(R.string.chat_copied),
                                        Toast.LENGTH_SHORT
                                    )
                                        .show()
                                }
                                vibrator.vibrate(100)
                            }
                        }
                    }

                    override fun onRegenerateVisible(isVisible: Boolean) = Unit

                    override fun onRemoveLimitsShow(isAuto: Boolean, isShowAdLimit: Boolean) = Unit

                    override fun onGoingToBilling() = Unit

                    override fun onClickGood(item: ChatItem) = Unit

                    override fun onClickBad(item: ChatItem) = Unit

                    override fun onShareContent(item: ChatItem) {
                        try {
                            val result =
                                "${item.content?.answer ?: ""}\n\n${getString(R.string.share_prefix)} $MYSELF_URL_IN_GOOGLE_PLAY"
                            val intent = Intent()
                            intent.action = Intent.ACTION_SEND
                            intent.putExtra(Intent.EXTRA_TEXT, result)
                            intent.type = "text/plain"
                            startActivity(Intent.createChooser(intent, "Share to"))
                        } catch (_: Exception) {
                            // do nothing now
                        }
                    }
                }
            }
            historyRecycler.layoutManager =
                LinearLayoutManager(this@HistoryActivity, LinearLayoutManager.VERTICAL, false)
            historyRecycler.adapter = adapter

            tvShare.setOnClickListener {
                clickShare()
            }

            tvNewChat.setOnClickListener {
                AnalyticsEvents.AC_HISTORY_NEWCHAT_CLICK.logEvent()
                startActivity(
                    Intent(this@HistoryActivity, ChatActivity::class.java)
                )
                finish()
            }
        }

        val json = intent?.getStringExtra(KEY_HISTORY_DATA)
        json?.let {
            val typeToken: TypeToken<List<ChatItem>> = object : TypeToken<List<ChatItem>>() {}
            val data = Gson().fromJson<List<ChatItem>>(json, typeToken.type)
            adapter.replaceMessageList(data)
        }
    }

    private fun clickShare() {
        selectShareFragment = SelectShareBottomDialogFragment()
        selectShareFragment?.listener =
            object : SelectShareBottomDialogFragment.OnFunctionListener {
                override fun onTxtClick() {
                    val data = adapter.data
                    val builder = StringBuilder()
                    data.forEach {
                        if (it.type == ChatType.TYPE_QUESTION || it.type == ChatType.TYPE_PHOTO) {
                            val content = it.content?.answer ?: ""
                            builder.append("Q: $content")
                            builder.append("\n\n")
                        } else if (it.type == ChatType.TYPE_ANSWER && !it.isLoading) {
                            val content = it.content?.answer ?: ""
                            builder.append("A: $content")
                            builder.append("\n\n")
                        }
                    }
                    builder.append("${getString(R.string.share_prefix)} $MYSELF_URL_IN_GOOGLE_PLAY")
                    val result = builder.toString()
                    try {
                        val intent = Intent()
                        intent.action = Intent.ACTION_SEND
                        intent.putExtra(Intent.EXTRA_TEXT, result)
                        intent.type = "text/plain"
                        startActivity(Intent.createChooser(intent, "Share to"))
                    } catch (_: Exception) {
                        // do nothing now
                    }
                    selectShareFragment?.dismissAllowingStateLoss()
                }

                override fun onPhotoClick() {
                    doShareChat()
                    selectShareFragment?.dismissAllowingStateLoss()
                }
            }
        selectShareFragment?.show(supportFragmentManager, "")
    }

    private fun doShareChat() {

        if (isHandleShare) {
            return
        }
        AnalyticsEvents.AC_HISTORY_SHARE_CLICK.logEvent()
        isHandleShare = true
        lifecycleScope.launch {
            var uri: Uri
            val bitmap = BitmapUtils.shotRecyclerView(binding.historyRecycler)
            if (bitmap == null) {
                isHandleShare = false
                return@launch
            }
            withContext(Dispatchers.IO) {
                val dir = File(FileUtils.getCacheDir(this@HistoryActivity), "pic")
                val file = File(dir, "share.jpeg")
                if (!dir.exists()) {
                    dir.mkdirs()
                }
                if (!file.exists() && dir.isFile) {
                    file.createNewFile()
                }
                BitmapUtils.bitmapToFile(bitmap, file)
                uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    FileProvider.getUriForFile(
                        this@HistoryActivity,
                        "$packageName.fileprovider",
                        file
                    )
                } else {
                    Uri.fromFile(file)
                }

            }
            try {
                val intent = Intent()
                intent.action = Intent.ACTION_SEND
                intent.putExtra(Intent.EXTRA_STREAM, uri)
                intent.type = "image/*"
                startActivity(Intent.createChooser(intent, "Share to"))
            } catch (_: Exception) {
                // do nothing now
            } finally {
                delay(1500L) //延时保证选择应用底部弹窗完全获取焦点
                isHandleShare = false
            }
        }
    }


    companion object {
        const val KEY_HISTORY_DATA = "key_history_data"
    }

}